﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using EPiServer.ServiceLocation;

namespace EPiBoost.Core.Web
{
	
    public static class ServiceLocatorExtensions
    {
        internal static T GetService<T>(this HttpContextBase httpContext, string key = null)
        {
            IServiceLocator serviceLocator = httpContext.GetServiceLocator();
            if (key == null)
            {
                return serviceLocator.GetInstance<T>();
            }
            return serviceLocator.GetInstance<T>(key);
        }

        internal static IServiceLocator GetServiceLocator(this HttpContextBase httpContext)
        {
            IServiceLocator locator = null;
            if (httpContext != null)
            {
                locator = httpContext.Items["serviceLocator"] as IServiceLocator;
            }
            return (locator ?? ServiceLocator.Current);
        }

        internal static IEnumerable<T> GetServices<T>(this HttpContextBase httpContext)
        {
            return httpContext.GetServiceLocator().GetAllInstances<T>();
        }

        internal static void SetServiceLocator(this HttpContextBase httpContext, IServiceLocator serviceLocator)
        {
            httpContext.Items["serviceLocator"] = serviceLocator;
        }
    }
}

